package com.boot.security.server.service.impl.mffl.MfflImageAndText;

import com.boot.security.server.dao.UserDao;
import com.boot.security.server.dao.mffl.*;
import com.boot.security.server.model.SysUser;
import com.boot.security.server.model.mffl.*;
import com.boot.security.server.model.mffl.Vo.MfflContractVo;
import com.boot.security.server.service.impl.mffl.LwyerPersonalService.LwyerPersonalService;
import com.boot.security.server.service.impl.mffl.MfflChatContent.MfflChatContentService;
import com.boot.security.server.service.impl.mffl.MfflSystemMessages.MfflSystemMessagesImpl;
import com.boot.security.server.service.impl.mffl.Mfflpublic.publicService;
import com.boot.security.server.service.impl.mffl.WXPay.WXPayService;
import com.boot.security.server.utils.UserUtil;
import com.boot.security.server.utils.mffl.ProjectUtil;
import com.boot.security.server.utils.mffl.ReturnBean;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.boot.security.server.service.impl.mffl.MfflSystemMessages.MfflSystemMessagesImpl;
import com.boot.security.server.service.impl.mffl.Mfflpublic.publicService;

@Service
public class MfflImageAndTextService {

    //律师收费标准
    @Autowired
    private LwyerPersonalService lwyerPersonalservice;

    //公共功能
    @Autowired
    private publicService publicService;


    //配置微信支付随机数
    @Value("${Pay.attach}")
    private String attach;

    //服务类型
    @Autowired
    MfflTypeDao mffltypedao;

    //用户表
    @Autowired
    MfflUserDao mffluserdao;

    //系统表
    @Autowired
    UserDao userdao;

    //订单
    @Autowired
    private MfflOrderDao mfflOrderDao;

    @Autowired
    private MfflServiceDao mfflServiceDao;

    //微信支付
    @Autowired
    private WXPayService wxpayservice;

    //支入支出表
    @Autowired
    private MfflProfitDao mfflProfitDao;

    //及时通讯表
    @Autowired
    MfflMappingDao mfflmappingdao;

    //服务
    @Autowired
    MfflServiceDao mfflservicedao;

    //推送
    @Autowired
    private MfflChatContentService mfflchatcontentService;

    //图文咨询支付
    @Transactional(rollbackFor = Exception.class)
    public ReturnBean imageandtextOrder(Long lawyerid) throws Exception {

        try {
            ReturnBean returnBean = new ReturnBean();
            //律师是否存在
            mfflUserSimple lawyer = mffluserdao.getLawyer(lawyerid.intValue());
            if (lawyer == null) {
                returnBean.setReturnBean("116");
                return returnBean;
            }
            if (lawyer.getLawyerinspect() != 1) {
                returnBean.setReturnBean("137");
                return returnBean;
            }
            //律师收费标准
            MfflLwyerPersonalService mps = lwyerPersonalservice.getLawyerServiceMoney(lawyerid.intValue(), 6);
            if (mps == null) {
                returnBean.setReturnBean("112");
                return returnBean;
            }

            //获取当前用户
            SysUser sysUser = UserUtil.getLoginUser();

            //即时通讯
            MfflMapping mfflMapping = mfflmappingdao.getuserLawyermapping(sysUser.getId().intValue(), lawyerid.intValue());
            MfflMapping Mapping = new MfflMapping();
            if (mfflMapping == null) {
                //新增
                Mapping.setUserId(sysUser.getId().intValue());
                Mapping.setLawyerId(lawyerid.intValue());
                Mapping.setFirstTime((int)(Long.parseLong(mps.getFreeApplyTime())/1000));//毫秒转为秒
                Date date = new Date();
                Mapping.setUpdateTime(date);
                mfflmappingdao.save(Mapping);
            }

            //创建订单
            MfflOrder mfflOrder = new MfflOrder();
            mfflOrder.setPayNumber("");
            String payMerchantNumber = ProjectUtil.payMerchantNumber(); //获取商户订单号
            mfflOrder.setPayMerchantNumber(payMerchantNumber);  //获取商户订单号
            mfflOrder.setServierId(6);                     //6图文资讯
            mfflOrder.setServiceName("图文资讯");           //服务名称
            mfflOrder.setMoney(mps.getMoney());            //金额
            mfflOrder.setUserid(sysUser.getId().intValue());
            Date date = new Date();
            mfflOrder.setCreateTime(date);
            mfflOrder.setUpdtaeTime(date);
            mfflOrder.setDeleteTime(date);
            mfflOrder.setDeleteStae(1);                         //是否删除(0删除,1正常)
            mfflOrder.setTypeid(0);                             //类型
            mfflOrder.setState(0);                              //0待支付，1支付，2退款
            mfflOrder.setProductId(mfflMapping == null ? Mapping.getId().intValue() : mfflMapping.getId().intValue());//订单关联
            mfflOrderDao.save(mfflOrder);
            returnBean.setDatas(payMerchantNumber);
            return returnBean;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("下单未知错误");
        }
    }


    //微信支付
    @Transactional(rollbackFor = Exception.class)
    public ReturnBean ServicePay(String payMerchantNumber, String notifyurl) {
        ReturnBean returnBean = wxpayservice.WXPay(notifyurl, "图文资讯", payMerchantNumber);
        if ("123".equals(returnBean.getErrCode())) {
            //订单号重复支付修改订单号，修改数据订单号
            //修改合同订单号  修改order订单号
            //订单操作
            MfflOrder Order = mfflOrderDao.getBypaymerchantnumber(payMerchantNumber);

            //重新生成订单号
            String newpayMerchantNumber = ProjectUtil.payMerchantNumber();

            //创建一个实体，防止在修改过程中其他信息改变的风险
            MfflOrder mfflOrder = new MfflOrder();
            mfflOrder.setId(Order.getId());
            mfflOrder.setPayMerchantNumber(newpayMerchantNumber);
            mfflOrder.setUpdtaeTime(new Date());
            mfflOrderDao.update(mfflOrder);

            ReturnBean returnbean = new ReturnBean();
            returnbean.setReturnBean("142");
            returnbean.setDatas(new HashMap<String, String>() {{
                put("newpayMerchantNumber", newpayMerchantNumber);
            }});
            return returnbean;
        }
        return returnBean;
    }


    //微信支付回调
    @Transactional(rollbackFor = Exception.class)
    public boolean WechatPayCallback(Map<String, String> map) throws Exception {
        System.out.println("访问回调");
        System.out.println(map);
        String paymerchantnumber = map.get("out_trade_no");//商户订单号
        String payNumber = map.get("transaction_id");      //交易单号
        String nonceStr = map.get("attach");      //随机数
        //验证随机数
        if (!attach.equals(nonceStr)) {
            System.out.println("验证随机数不通过");
            return false;
        }

        try {
            //订单操作
            MfflOrder Order = mfflOrderDao.getBypaymerchantnumber(paymerchantnumber);
            //即时通讯
            MfflMapping mfflMapping = mfflmappingdao.getById(Order.getProductId().longValue());
            //律师收费标准
            MfflLwyerPersonalService mps = lwyerPersonalservice.getLawyerServiceMoney(mfflMapping.getLawyerId(), 6);

            //如果已支付返回true
            if (!(Order.getState() == 0 || Order.getState() == 5)) {
                return true;
            }

            //创建一个实体，防止在修改过程中其他信息改变的风险
            MfflOrder mfflOrder = new MfflOrder();
            mfflOrder.setId(Order.getId());
            mfflOrder.setPayNumber(payNumber);
            mfflOrder.setUpdtaeTime(new Date());
            mfflOrder.setState(1);
            mfflOrderDao.update(mfflOrder);

            //更新对应关系表
            MfflMapping Mapping = new MfflMapping();
            Mapping.setId(mfflMapping.getId());
            Mapping.setFirstTime(((mps.getCompany() * 60) * 60) + mfflMapping.getFirstTime());
            Mapping.setUpdateTime(new Date());
            mfflmappingdao.update(Mapping);


            //插入 支入支出表
            List<MfflProfit> byOrderId = mfflProfitDao.getOrderId(mfflOrder.getId().intValue());
            if (byOrderId.size() == 0) {
                //图文咨询信息
                MfflService Service = mfflServiceDao.getById((long) 6);

                MfflProfit mp = new MfflProfit();
                mp.setOrderId(mfflOrder.getId().intValue());
                mp.setUserId(mfflMapping.getUserId()); //用户id
                mp.setServciceName(Service.getName());
                mp.setState(0);               //0支出，1收益,
                mp.setMoney(Order.getMoney());  //支出不扣点
                mp.setSettlement(1);          //0未结算，1已经算
                Date date = new Date();
                mp.setCreateTime(date);
                mp.setSettlementTime(date);
                mp.setDeduction(0.0);
                mp.setUpdateTime(date);
                mfflProfitDao.save(mp);

                //律师支出
                MfflProfit mlp = new MfflProfit();
                mlp.setOrderId(Order.getId().intValue());
                mlp.setUserId(mfflMapping.getLawyerId()); //律师id
                mlp.setServciceName(Service.getName());
                mlp.setState(1);               //0支出，1收益,
                mlp.setMoney(Order.getMoney());   //律师收益显示已扣点金额
                mlp.setSettlement(0);          //0未结算，1已经算
                mlp.setCreateTime(date);
                mlp.setSettlementTime(date);
                mlp.setDeduction(0.0);   //平台扣点金额
                mlp.setUpdateTime(date);
                mfflProfitDao.save(mlp);


                //修改律师个人账户金额
                MfflUser userInfoAll = mffluserdao.getmffluser(mfflMapping.getLawyerId());
                MfflUser mu = new MfflUser();
                mu.setId(userInfoAll.getId());
                mu.setMoney(ProjectUtil.addition(userInfoAll.getMoney() , Order.getMoney()));
                mu.setUpdateTime(new Date());
                mffluserdao.update(mu);
                //推送
                mfflchatcontentService.sendMessage(Order.getServierId(),mfflMapping.getLawyerId(),"[图文咨询]图文咨询服务被购买");
            }
        } catch (Exception e) {
            e.printStackTrace();
            //防止意外错误
            throw new Exception("支付回调错误");
        }
        return true;
    }


    /**
     * 查询订单状态
     * <p>
     * 如果查询微信订单为已支付并且本地order未改变，则修改状态
     *
     * @param payMerchantNumber
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ReturnBean orderquery(String payMerchantNumber) throws Exception {
        ReturnBean returnBean = new ReturnBean();
        try {
            Map<String, String> orderquery = wxpayservice.orderquery(payMerchantNumber);
            MfflOrder Order = mfflOrderDao.getByPaymerchantNumberlocking(payMerchantNumber);
            if (!(orderquery.containsKey("trade_state") && orderquery.get("trade_state").equals("SUCCESS"))) {
                MfflOrder mfflOrder = new MfflOrder();
                mfflOrder.setId(Order.getId());
                mfflOrder.setState(5);//支付中
                mfflOrder.setUpdtaeTime(new Date());
                mfflOrderDao.update(mfflOrder);
                returnBean.setDatas(orderquery);
                return returnBean;
            }

            //订单操作
            String payNumber = orderquery.get("transaction_id");
            //如果状态未改变则改变状态
            if (Order.getState() == 0 || Order.getState() == 5) {
                //创建一个实体，防止在修改过程中其他信息改变的风险
                MfflOrder mfflOrder = new MfflOrder();
                mfflOrder.setId(Order.getId());
                mfflOrder.setPayNumber(payNumber);
                mfflOrder.setUpdtaeTime(new Date());
                mfflOrder.setState(1);
                mfflOrderDao.update(mfflOrder);

                //即时通讯
                MfflMapping mfflMapping = mfflmappingdao.getById(Order.getProductId().longValue());
                //律师收费标准
                MfflLwyerPersonalService mps = lwyerPersonalservice.getLawyerServiceMoney(mfflMapping.getLawyerId(), 6);

                //更新
                MfflMapping Mapping = new MfflMapping();
                Mapping.setId(mfflMapping.getId());
                Mapping.setFirstTime(((mps.getCompany() * 60) * 60) + mfflMapping.getFirstTime());
                Mapping.setUpdateTime(new Date());
                mfflmappingdao.update(Mapping);


                //插入 支入支出表
                List<MfflProfit> byOrderId = mfflProfitDao.getOrderId(mfflOrder.getId().intValue());
                if (byOrderId.size() == 0) {
                    //图文咨询信息
                    MfflService Service = mfflServiceDao.getById((long) 6);

                    MfflProfit mp = new MfflProfit();
                    mp.setOrderId(mfflOrder.getId().intValue());
                    mp.setUserId(mfflMapping.getUserId()); //用户id
                    mp.setServciceName(Service.getName());
                    mp.setState(0);               //0支出，1收益,
                    mp.setMoney(Order.getMoney());  //支出不扣点
                    mp.setSettlement(1);          //0未结算，1已经算
                    Date date = new Date();
                    mp.setCreateTime(date);
                    mp.setSettlementTime(date);
                    mp.setDeduction(0.0);
                    mp.setUpdateTime(date);
                    mfflProfitDao.save(mp);

                    //律师支出
                    MfflProfit mlp = new MfflProfit();
                    mlp.setOrderId(Order.getId().intValue());
                    mlp.setUserId(mfflMapping.getLawyerId()); //律师id
                    mlp.setServciceName(Service.getName());
                    mlp.setState(1);               //0支出，1收益,
                    mlp.setMoney(Order.getMoney());   //律师收益显示已扣点金额
                    mlp.setSettlement(0);          //0未结算，1已经算
                    mlp.setCreateTime(date);
                    mlp.setSettlementTime(date);
                    mlp.setDeduction(0.0);   //平台扣点金额
                    mlp.setUpdateTime(date);
                    mfflProfitDao.save(mlp);


                    //修改律师个人账户金额
                    MfflUser userInfoAll = mffluserdao.getmffluser(mfflMapping.getLawyerId());
                    MfflUser mu = new MfflUser();
                    mu.setId(userInfoAll.getId());
                    mu.setMoney(ProjectUtil.addition(userInfoAll.getMoney() , Order.getMoney()));
                    mu.setUpdateTime(new Date());
                    mffluserdao.update(mu);
                    mfflchatcontentService.sendMessage(Order.getServierId(),mfflMapping.getLawyerId(),"[图文咨询]图文咨询服务被购买");
                }
                return returnBean;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
        returnBean.setReturnBean("141");
        return returnBean;
    }
}
